import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import { ModifyPageService } from './modify-page.service';
import { AppPaginationComponent, PaginationModel } from "app/widgets/pagination/pagination.component";
import { ModifyRemindPageComponent } from "../../modify/modify-remind-page/modify-remind-page.component";
import { environment } from 'environments/environment';
import { ViewComponent } from "../../../modal/view/view.component";
import { EditComponent } from "../../../modal/edit/edit.component";
import { FlowComponent } from "../../../modal/flow/flow.component";
import { SingleComponent } from "../../../modal/single/single.component";
import { HistoryComponent } from "../../../modal/history/history.component";
import { QueryComponent } from "../../../modal/query/query.component";
import { SubmitComponent } from "../../../modal/submit/submit.component";
import { InvestService } from "../../../invest.service";
import * as _ from 'lodash';
import { DataService } from 'app/services/data.service';
import { Util } from 'app/common/util';
import { TableComponent } from "../../../modal/table/table.component";

@Component({
  selector: 'app-modify-page',
  templateUrl: './modify-page.component.html',
  styleUrls: ['./modify-page.component.scss'],
  providers: [ModifyPageService]
})
export class ModifyPageComponent implements OnInit {
  // 搜索模版
  @ViewChild("query", { read: ViewContainerRef })
  query: ViewContainerRef;
  queryComponent: ComponentRef<QueryComponent>;
  // 查看模版
  @ViewChild("view", { read: ViewContainerRef })
  view: ViewContainerRef;
  viewComponent: ComponentRef<ViewComponent>;
  // 修改模版
  @ViewChild("edit", { read: ViewContainerRef })
  edit: ViewContainerRef;
  editComponent: ComponentRef<EditComponent>;
  // 提交、保存并提交、撤销模版
  @ViewChild("submit", { read: ViewContainerRef })
  submit: ViewContainerRef;
  submitComponent: ComponentRef<SubmitComponent>;
  // 查看流程状态模版
  @ViewChild("flow", { read: ViewContainerRef })
  flow: ViewContainerRef;
  flowComponent: ComponentRef<FlowComponent>;
  // 查看单条基金变更模版
  @ViewChild("single", { read: ViewContainerRef })
  single: ViewContainerRef;
  singleComponent: ComponentRef<SingleComponent>;
  // 查看历史变更模版
  @ViewChild("history", { read: ViewContainerRef })
  history: ViewContainerRef;
  historyComponent: ComponentRef<HistoryComponent>;
  // 提醒页面模版
  @ViewChild("modifyRemindPage", { read: ViewContainerRef })
  modifyRemindPage: ViewContainerRef;
  modifyRemindPageComponent: ComponentRef<ModifyRemindPageComponent>;
  // 模版
  @ViewChild("modifyTable", { read: ViewContainerRef })
  modifyTable: ViewContainerRef;
  modifyTableComponent: ComponentRef<TableComponent>;
  // lodash
  public _: any = _;
  // 菜单数据
  public menuData: any;
  // 菜单权限set
  public menuResourceSet: any = [];
  // 列表是否全选
  public isCheckedAll = false;
  // 列表新数据
  public dataList: any = [];
  // 列表旧数据，用于标红对比
  public odataList: any = {};
  // 克隆列表新数据,用于页面保存、提交时对比判断是否有修改
  public cloneList: any = [];
  // 克隆列表新数据,用于页面数据标红对比
  public isChangeList: any = [];
  // 用于是否显示下拉框
  public isEditList: any = [];
  // 分页列表post
  public getBody: any = {
    pageIndex: 1,
    pageSize: 20,
    sFullName: '',
    sFundCode: '',
    sFundType: '',
    type: '',
    sStatus: [],
    sSteps: []
  }
  // 列表分页配置
  public listPageInfo = {
    currentPageNum: 1,
    pageSize: 20,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 20, 50, 100]
  }
  // 基金状态下拉框值
  public fundList: any = [];
  // 字典值
  public dictionaryList: any = {
    INVEST_STATUS: []
  };
  // 批量修改下拉框值
  public f1: any = '';
  public f2: any = '';
  public f3: any = '';
  // 用于判断是模态框查询还是页面查询
  public isQuery: any = false;
  public user: any;

  constructor(
    public modifyPageService: ModifyPageService,
    public resolver: ComponentFactoryResolver,
    public investService: InvestService,
    public dataService: DataService,
  ) {
    let that = this;
    // 用于指标修改/保存/提交/撤销操作后刷新列表
    this.investService.targetEdit = new EventEmitter();
    this.investService.targetEdit.subscribe((data: any) => {
      if (data == 'refresh') {
        that.list();
      }
    })
    // 用于触发搜索模态框查询
    this.investService.query = new EventEmitter();
    this.investService.query.subscribe((data: any) => {
      if (data == 'modify') {
        // 切换tab重置页码和页数
        that.isQuery = true;
        that.setFundStatus(that.investService.queryBody.sFundType);
        that.list();
      }
    })
  }

  ngOnInit() {
    let that = this;
    // 权限处理
    this.dataService.initTree.subscribe((data) => {
      if (data) {
        let SessionMenuData = sessionStorage.getItem('menu');
        this.menuData = JSON.parse(SessionMenuData)
        this.menuResourceSet = [];
        _.forEach(this.menuData, (item, index) => {
          if (item.sName == '风控管理') {
            _.forEach(item.children, (it, idx) => {
              if (it.sName == '投资范围指标') {
                _.forEach(it.children, (ite, i) => {
                  if (ite.sName == '指标修改') {
                    that.menuResourceSet = ite.resourceSet
                    sessionStorage.setItem('btn-rcmi', this.menuResourceSet);
                  }
                })
              }
            })
          }
        })
      }
    })
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData)
    this.menuResourceSet = [];
    _.forEach(this.menuData, (item, index) => {
      if (item.sName == '风控管理') {
        _.forEach(item.children, (it, idx) => {
          if (it.sName == '投资范围指标') {
            _.forEach(it.children, (ite, i) => {
              if (ite.sName == '指标修改') {
                that.menuResourceSet = ite.resourceSet
                sessionStorage.setItem('btn-rcmi', this.menuResourceSet);
              }
            })
          }
        })
      }
    })
    // 加载table
    this.showModifyTable();
    // 基金状态
    this.getFundStatus();
    // 字典值
    this.dictionaryList = JSON.parse(localStorage.getItem("dictionaryList"));
    // 获取当前用户
    this.user = sessionStorage.getItem('username');
    this.list();
  }
  ngAfterViewInit() {
    let that = this;
    // 加载指标状态下拉框
    setTimeout(function () {
      window['$']('#modifyTargetSteps').selectpicker('destroy');
      that.loadSelect(that.dictionaryList.INVEST_STATUS, 'modifyTargetSteps');
    }, 1);
  }
  // 获取基金状态下拉框
  getFundStatus() {
    let that = this;
    this.modifyPageService.getFundStatus().subscribe(data => {
      if (data) {
        that.fundList = data.subTree;
        localStorage.setItem("fundList", JSON.stringify(that.fundList));
      }
    })
  }
  // 基金状态下拉框赋值
  setFundStatus(fundType: any) {
    let that = this;
    if (fundType == '') {
      that.getBody.sStatus = [];
      window['$']('#modifyFundStatus').selectpicker('destroy');
    } else {
      _.forEach(this.fundList, item => {
        if (item.sFundType == fundType) {
          that.getBody.sStatus = [];
          setTimeout(function () {
            window['$']('#modifyFundStatus').selectpicker('destroy');
            that.loadSelect(item.subTree, 'modifyFundStatus');
          }, 1);
        }
      })
    }
  }
  // select插件，支持多选，在html配置multiple属性，传入字典值、id即可。在ngOninit初始化函数。
  loadSelect(field, id, width?) {
    var html = '';
    for (var i = 0; i < field.length; i++) {
      html += "<option value='" + field[i].sItemKey + "'>" + field[i].sItemValue + "</option>";
    }
    window['$']("#" + id).html(html);
    window['$']('#' + id).selectpicker({
      size: "8",
      actionsBox: "true",
      title: "请选择",
      selectAllText: "全选",
      deselectAllText: "取消全选",
      width: width ? width : 120,
      liveSearch: true, //搜索功能
      dropupAuto: false
    });

  }
  // 获取列表数据
  getList(index: any) {
    if (index == '8') {
      this.isQuery = false;
      this.showTargetModifyRemind(index);
    } else {
      this.getBody.sFundType = index;
      this.isQuery = false;
      this.setFundStatus(index);
      this.list(1);
    }
  }
  // 分页列表
  list(pageNum?, pageSize?) {
    let that = this;
    let postBody: any;
    // this.isCheckedAll = false;
    if (this.isQuery) {
      // 清空页面查询条件
      this.getBody.sFullName = '';
      this.getBody.sFundCode = '';
      this.getBody.sStatus = [];
      this.getBody.sStep = '';
      // 查询条件非空转码
      _.forIn(this.investService.queryBody, (value, key) => {
        if (key == 'sStatus' || key == 'nFundNo') {
          // 基金状态下拉框不做处理
        } else {
          that.investService.queryBody[key] = _.trim(that.investService.queryBody[key]);
        }
      })
      // 在途/全部
      this.investService.queryBody['type'] = this.getBody.type;
      postBody = _.cloneDeep(this.investService.queryBody);
    } else {
      this.getBody.sFullName = _.trim(this.getBody.sFullName);
      postBody = _.cloneDeep(this.getBody);
    }
    postBody.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
    postBody.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize;
    // tab切换
    this.activeTab(postBody.sFundType);
    new Promise((resolve, reject) => {
      this.modifyPageService.list(postBody).subscribe(data => {
        if (data) {
          that.dataList = data.newObject.list;
          that.odataList = data.oldObject;
          that.listPageInfo.currentPageNum = data.newObject.pageNum;
          that.listPageInfo.totalPages = data.newObject.pages;
          that.listPageInfo.total = data.newObject.total;
          that.listPageInfo.startRow = data.newObject.startRow;
          that.listPageInfo.endRow = data.newObject.endRow;
          // 将所有null转化为空''
          _.forEach(that.dataList, item => {
            _.forIn(item, (value, key) => {
              if (value == null) {
                item[key] = '';
              }
            })
          })
          _.forEach(that.odataList, item => {
            _.forIn(item, (value, key) => {
              if (value == null) {
                item[key] = '';
              }
            })
          })
          resolve(data);
        }
      })
    }).then(data => {
      // 克隆列表新数据,用于页面保存、提交时对比判断是否有修改
      that.cloneList = _.cloneDeep(that.dataList);
      // 克隆列表新数据,用于页面数据标红对比
      that.isChangeList = _.cloneDeep(that.dataList);
      // 用于是否显示下拉框
      that.isEditList = _.cloneDeep(that.dataList);
      // 对比标红
      _.forEach(that.dataList, (item, index) => {
        _.forIn(item, (value, key) => {
          if (value == that.odataList[item.nFundNo][key]) {
            that.isChangeList[index][key] = false;
            that.isEditList[index][key] = 'no';
          } else {
            that.isChangeList[index][key] = true;
            that.isEditList[index][key] = 'no';
          }
        })
      })
    }).then(data => {
      that.modifyTableComponent.instance.isCheckedAll = false;
      that.modifyTableComponent.instance.dataList = _.cloneDeep(that.dataList);
      that.modifyTableComponent.instance.cloneList = _.cloneDeep(that.dataList);
      that.modifyTableComponent.instance.isChangeList = _.cloneDeep(that.isChangeList);
      that.modifyTableComponent.instance.isEditList = _.cloneDeep(that.isEditList);
    })
  }
  // 分页
  sizeChange(pageSize: number) {
    if (pageSize !== this.listPageInfo.pageSize) {
      this.listPageInfo.pageSize = pageSize;
      this.list();
    }
  }
  // 分页
  pageNavigation(currentPageNum: number) {
    this.listPageInfo.currentPageNum = currentPageNum;
    this.list(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
  }
  // 在途/全部
  onWay(type: any) {
    let that = this;
    switch (type) {
      case 'onWay':
        that.getBody.type = '1';
        that.list();
        break;
      case 'all':
        that.getBody.type = '';
        that.list();
        break;
    }
  }
  // 修改
  modify(type, item?) {
    let that = this;
    let obj: any;
    let checkedItem = [];
    switch (type) {
      case 'button':
        _.forEach(this.modifyTableComponent.instance.dataList, it => {
          if (it.isChecked) {
            checkedItem.push(it);
          }
        });
        if (checkedItem.length == 1) {
          that.modifyCheck(checkedItem[0]);
        } else if (checkedItem.length < 1) {
          window['swal']("提示", "请选择一条记录", "warning");
        } else if (checkedItem.length > 1) {
          window['swal']("提示", "只能选择一条记录", "warning");
        }
        break;
      case 'dbclick':
        that.modifyCheck(item);
        break;
    }
  }
  // 修改
  modifyCheck(item) {
    let arr = [];
    // 正常状态的数据不作判断
    if (item.sStep == '1') {
      arr.push(item)
      this.showEdit(arr);
    } else {
      // 先判断数据操作人是否为当前用户、null、'',再判断指标状态
      if (item.sOpr == this.user || item.sOpr == null || item.sOpr == '') {
        if (item.sStep == '2') {
          arr.push(item)
          this.showEdit(arr);
        } else {
          window['swal']("提示", "请选择正常或变更记录修改", "warning");
        }
      } else {
        window['swal']("提示", "不能修改 " + item.sOpr + " 修改过的数据", "warning");
      }
    }
  }
  // 撤销
  cancel() {
    let that = this;
    let checkedItem = [];
    // let fundNoList = [];
    let saveItem = [];
    _.forEach(this.modifyTableComponent.instance.dataList, item => {
      if (item.isChecked) {
        checkedItem.push(item);
        saveItem.push(that.odataList[item.nFundNo]);         // 用于最后保存提交,旧数据
        saveItem.push(item);                                 // 用于最后保存提交,新数据
      }
    });
    if (checkedItem.length == 1) {
      if (checkedItem[0].sStep == null || checkedItem[0].sStep == '') {
        window['swal']("提示", "指标状态为空", "warning");
      } else if (checkedItem[0].sStep == '1') {
        window['swal']("提示", "指标状态为正常不可撤销", "warning");
      } else if (checkedItem[0].sStep == '2') {
        // 变更状态只能当前操作人,null,''
        if (checkedItem[0].sOpr == this.user || checkedItem[0].sOpr == null || checkedItem[0].sOpr == '') {
          this.showSubmit(saveItem, 'cancel');
        } else {
          window['swal']("提示", "不能撤销 " + checkedItem[0].sOpr + " 修改过的数据", "warning");
        }
      } else if (checkedItem[0].sStep == '3' || checkedItem[0].sStep == '4') {
        // 复核状态任何人都可以撤销
        this.showSubmit(saveItem, 'cancel');
      }
    } else if (checkedItem.length < 1) {
      window['swal']("提示", "请选择一条记录", "warning");
    } else if (checkedItem.length > 1) {
      window['swal']("提示", "只能选择一条记录", "warning");
    }
  }
  // 保存
  save() {
    let that = this;
    let checkedItem = [];
    let sStepArry = [];
    let saveItem = [];
    let cloneItem = [];
    _.forEach(this.modifyTableComponent.instance.dataList, (item, index) => {
      if (item.isChecked) {
        // 防止删除其他操作有用属性，另起变量赋值
        let it = _.cloneDeep(item);
        // 产品内码赋值给nIxId，假设是新增，后台需要这个字段进行关联
        it.nIxId = it.nFundNo;
        delete it.sFundType;
        delete it.sFundCode;
        delete it.sFullName;
        delete it.sStatus;
        delete it.changeInitiator;
        delete it.changeDate;
        delete it.reviewer;
        delete it.auditDate;
        delete it.sOprStateZh;
        delete it.sStep;
        delete it.isChecked;
        delete it.nFundNo;
        delete it.riskAuditOpr;
        delete it.riskAuditDate;
        delete it.sStepZh;
        delete it.sFundTypeZh;
        delete it.sFlowStepZh;
        delete it.sOprZh;
        checkedItem.push(it);                   // 用于最后保存
        sStepArry.push(item.sStep);             // 用于判断状态
        saveItem.push(_.cloneDeep(item));       // 用于数据对比
        cloneItem.push(that.cloneList[index])   // 用于数据对比
      }
    });
    if (checkedItem.length == 0) {
      window['swal']("提示", "请选择一条或多条记录", "warning");
    } else {
      // 判断变更中数据是否包含其他人的
      if (this.isCludesOpr(saveItem)) {
        // 判断数据是否有修改
        if (this.isChangeInfo(saveItem, cloneItem, 'save')) {
          // 判断是否包含指标状态为风险管理部审核、指标复核的数据
          if (_.includes(sStepArry, '3') || _.includes(sStepArry, '4') || _.includes(sStepArry, null)) {
            window['swal']("提示", "请选择正常或变更的记录保存", "warning");
          } else {
            window['swal']({
              type: "warning",
              showCancelButton: true,
              confirmButtonText: "确认",
              cancelButtonText: "取消",
              closeOnConfirm: false,
              showLoaderOnConfirm: true,
              title: "提示",
              text: "是否确认保存?",
              html: true
            }, function (isConfirm) {
              if (isConfirm) {
                that.modifyPageService.save(checkedItem).subscribe(data => {
                  if (data) {
                    window['swal']("成功", "保存成功", "success");
                    that.list();
                  }
                })
              }
            })
          }
        }
      }
    }
  }
  // 提交、保存并提交
  saveOrSubmit(operate) {
    let that = this;
    let saveItem = [];
    let checkedItem = [];
    let sStepArry = [];
    let cloneItem = [];
    _.forEach(this.modifyTableComponent.instance.dataList, (item, index) => {
      if (item.isChecked) {
        sStepArry.push(item.sStep);             // 用于判断状态
        checkedItem.push(_.cloneDeep(item));    // 用于数据对比
        cloneItem.push(that.cloneList[index])   // 用于数据对比
        saveItem.push(that.odataList[item.nFundNo]);         // 用于最后保存提交,旧数据
        saveItem.push(item);                                 // 用于最后保存提交,新数据
      }
    });
    if (checkedItem.length == 0) {
      window['swal']("提示", "请选择一条或多条记录", "warning");
    } else {
      // 指标状态(1-正常,2-变更,3-风险管理部复核,4-指标复核)
      switch (operate) {
        case 'submits':
          // 判断变更中数据是否包含其他人的
          if (that.isCludesOpr(checkedItem)) {
            // 判断变更中的数据是否有修改，如果有修改提示先保存后提交
            if (that.isChangeInfo(checkedItem, cloneItem, 'submits')) {
              window['swal']("提示", "先保存再提交", "warning");
            } else {
              if (_.includes(sStepArry, '1') || _.includes(sStepArry, '3') || _.includes(sStepArry, '4') || _.includes(sStepArry, null)) {
                window['swal']("提示", "请选择变更记录提交", "warning");
              } else {
                that.showSubmit(saveItem, operate);
              }
            }
          }
          break;
        case 'saveSubmits':
          // 判断变更中数据是否包含其他人的
          if (that.isCludesOpr(checkedItem)) {
            // 判断数据是否有修改
            if (that.isChangeInfo(checkedItem, cloneItem, 'saveSubmits')) {
              if (_.includes(sStepArry, '3') || _.includes(sStepArry, '4') || _.includes(sStepArry, null)) {
                window['swal']("提示", "请选择正常或变更记录保存并提交", "warning");
              } else {
                that.showSubmit(saveItem, operate);
              }
            }
          }
          break;
      }
    }
  }
  // 判断变更的数据是否包含其他人的,saveItem为勾选的数据
  isCludesOpr(saveItem: any) {
    let that = this;
    let sOprList = [];
    _.forEach(saveItem, val => {
      // 指标状态为变更并且操作人不是当前用户
      if (val.sStep == '2' && val.sOpr != that.user && val.sOpr != null && val.sOpr != '') {
        sOprList.push(val.sOpr)
      }
    })
    if (sOprList.length > 0) {
      let sOprLists = sOprList.join(",");
      window['swal']("提示", "不能修改 " + sOprLists + " 修改过的数据", "warning");
      return false;
    } else {
      return true;
    }
  }
  // 循环对比对象,newList为新修改数组,oldList为旧克隆数组
  isChangeInfo(newList: any, oldList: any, operate: any) {
    let isEqualList = [];
    _.forEach(newList, (value, key) => {
      delete value.isChecked;
      if (Util.objectCheck(value, oldList[key])) {
        isEqualList.push(value.sFullName);
      }
    })
    if (isEqualList.length > 0) {
      let isEqualLists = isEqualList.join(",");
      if (operate == 'submits') {
        return false;
      } else {
        window['swal']("提示", isEqualLists + " 信息没有修改", "warning");
        return false;
      }
    } else {
      return true;
    }
  }
  // 显示模版
  showModel(type) {
    let that = this;
    let checkedItem = [];
    _.forEach(this.modifyTableComponent.instance.dataList, item => {
      if (item.isChecked) {
        checkedItem.push(item);
      }
    });
    if (checkedItem.length == 1) {
      switch (type) {
        case 'view':
          this.showView(checkedItem);
          break;
        case 'flow':
          this.showFlow(checkedItem[0]);
          break;
        case 'single':
          this.showSingle(checkedItem[0]);
          break;
      }
    } else if (checkedItem.length < 1) {
      window['swal']("提示", "请选择一条记录", "warning");
    } else if (checkedItem.length > 1) {
      window['swal']("提示", "只能选择一条记录", "warning");
    }
  }
  // 搜索模版
  showQuery() {
    if (this.queryComponent && this.queryComponent.instance) {
      this.queryComponent.destroy();
    }
    const queryComponent = this.resolver.resolveComponentFactory(QueryComponent);
    this.queryComponent = this.query.createComponent(queryComponent);
    this.queryComponent.instance.type = 'modify';
    window['$']('#query').modal('show');
  }
  // 查看模版
  showView(dataList) {
    if (this.viewComponent && this.viewComponent.instance) {
      this.viewComponent.destroy();
    }
    const viewComponent = this.resolver.resolveComponentFactory(ViewComponent);
    this.viewComponent = this.view.createComponent(viewComponent);
    this.viewComponent.instance.dataList = dataList;
    this.viewComponent.instance.type = 'modify';
    window['$']('#view').modal('show');
  }
  // 查看修改模版
  showEdit(dataList) {
    if (this.editComponent && this.editComponent.instance) {
      this.editComponent.destroy();
    }
    const editComponent = this.resolver.resolveComponentFactory(EditComponent);
    this.editComponent = this.edit.createComponent(editComponent);
    this.editComponent.instance.dataList = _.cloneDeep(dataList);
    window['$']('#edit').modal('show');
  }
  // 提交、保存并提交、撤销模版
  showSubmit(saveItem, operate) {
    if (this.submitComponent && this.submitComponent.instance) {
      this.submitComponent.destroy();
    }
    const submitComponent = this.resolver.resolveComponentFactory(SubmitComponent);
    this.submitComponent = this.submit.createComponent(submitComponent);
    this.submitComponent.instance.operate = operate;
    this.submitComponent.instance.dataList = _.cloneDeep(saveItem);
    window['$']('#submit').modal('show');
  }
  // 查看流程状态模版
  showFlow(item) {
    if (this.flowComponent && this.flowComponent.instance) {
      this.flowComponent.destroy();
    }
    const flowComponent = this.resolver.resolveComponentFactory(FlowComponent);
    this.flowComponent = this.flow.createComponent(flowComponent);
    this.flowComponent.instance.getFlowBody.nIjId = item.nIjId;
    this.flowComponent.instance.getFlowBody.nIxId = item.nFundNo;
    this.flowComponent.instance.getFlowBody.nFlowId = item.nFlowId;
    this.flowComponent.instance.getBody.nIjId = item.nIjId;
    this.flowComponent.instance.getBody.nIxId = item.nFundNo;
    this.flowComponent.instance.getBody.nFlowId = item.nFlowId;
    this.flowComponent.instance.type = 'modify';
    window['$']('#modifyTargetFlow').modal('show');
  }
  // 查看单条基金变更模版
  showSingle(item) {
    if (this.singleComponent && this.singleComponent.instance) {
      this.singleComponent.destroy();
    }
    const singleComponent = this.resolver.resolveComponentFactory(SingleComponent);
    this.singleComponent = this.single.createComponent(singleComponent);
    this.singleComponent.instance.getBody.nIxId = item.nIxId;
    this.singleComponent.instance.type = 'modify';
    window['$']('#single').modal('show');
  }
  // 查看历史变更
  historyChange() {
    let that = this;
    let nFundNolist = [];
    _.forEach(this.modifyTableComponent.instance.dataList, (item, index) => {
      if (item.isChecked) {
        nFundNolist.push(item.nFundNo);
      }
    });
    if (nFundNolist.length == 0) {
      this.showHistory('');
    } else {
      let nFundNolists = nFundNolist.join(",");
      this.showHistory(nFundNolists);
    }
  }
  // 查看历史变更模版
  showHistory(item) {
    if (this.historyComponent && this.historyComponent.instance) {
      this.historyComponent.destroy();
    }
    const historyComponent = this.resolver.resolveComponentFactory(HistoryComponent);
    this.historyComponent = this.history.createComponent(historyComponent);
    this.historyComponent.instance.getBody.nIxIds = item;
    this.historyComponent.instance.type = 'modify';
    window['$']('#history').modal('show');
  }
  // 提醒页面模版
  showTargetModifyRemind(index: any) {
    this.activeTab(index);
    if (this.modifyRemindPageComponent && this.modifyRemindPageComponent.instance) {
      this.modifyRemindPageComponent.destroy();
    }
    const modifyRemindPageComponent = this.resolver.resolveComponentFactory(ModifyRemindPageComponent);
    this.modifyRemindPageComponent = this.modifyRemindPage.createComponent(modifyRemindPageComponent);
  }
  // 模版
  showModifyTable() {
    if (this.modifyTableComponent && this.modifyTableComponent.instance) {
      this.modifyTableComponent.destroy();
    }
    const modifyTableComponent = this.resolver.resolveComponentFactory(TableComponent);
    this.modifyTableComponent = this.modifyTable.createComponent(modifyTableComponent);
    this.modifyTableComponent.instance.isEdit = 'yes';
    this.modifyTableComponent.instance.isShowCol1 = 'sFundTypeZh';
    this.modifyTableComponent.instance.isShowCol2 = 'sFullName';
    this.modifyTableComponent.instance.isShowCol3 = 'sStepZh';
  }
  // 导出指标
  exportTarget() {
    let that = this;
    let checkedItem = [];
    let postBody: any;
    _.forEach(this.modifyTableComponent.instance.dataList, item => {
      if (item.isChecked) {
        checkedItem.push(item.nFundNo);
      }
    })
    // 请求body
    if (this.isQuery) {
      postBody = _.cloneDeep(this.investService.queryBody);
      postBody['nFundNo'] = checkedItem;
      postBody['type'] = this.getBody.type,
        delete postBody.pageIndex;
      delete postBody.pageSize;
    } else {
      postBody = {
        "nFundNo": checkedItem,
        "sFullName": this.getBody.sFullName,
        "sFundCode": this.getBody.sFundCode,
        "sFundType": this.getBody.sFundType,
        "sStatus": this.getBody.sStatus,
        "type": this.getBody.type,
        "sSteps": this.getBody.sSteps
      }
    }
    // 请求Url
    let postUrl = environment.server + '/pms/v1/riskmanage/investJournal/exportInvestUpdata?token=' + sessionStorage.getItem('token');
    // 导出指标
    this.modifyPageService.exportTarget(postUrl, postBody, '导出指标');

  }
  // 导出历史明细
  exportHistory() {
    let that = this;
    let checkedItem = [];
    _.forEach(this.modifyTableComponent.instance.dataList, item => {
      if (item.isChecked) {
        checkedItem.push(item.nFundNo);
      }
    })
    let converItem = checkedItem.join(',');
    let getBody: any = {
      'nIxIds': converItem
    }
    const iframe = window['$']("<iframe id='downloadiframe'>");
    iframe.attr('style', 'display:none');
    //  转码，兼容ie
    getBody.sFullName = encodeURI(getBody.sFullName)
    iframe.attr('src', environment.server + '/pms/v1/riskmanage/investData/exportHistoryJournal?token=' + sessionStorage.getItem('token') + '&nIxIds=' + getBody.nIxIds);
    window['$']('body').append(iframe);
    setTimeout("$('#downloadiframe').remove()", 60000);
  }
  // 激活tab
  activeTab(sFundType: any) {
    let that = this;
    window['$']('#modify-ALL').removeClass('active');
    window['$']('#modify-GM').removeClass('active');
    window['$']('#modify-YDD').removeClass('active');
    window['$']('#modify-YDY').removeClass('active');
    window['$']('#modify-QYNJ').removeClass('active');
    window['$']('#modify-YLJ').removeClass('active');
    window['$']('#modify-SB').removeClass('active');
    window['$']('#modify-YLJJ').removeClass('active');
    window['$']('#tab1').removeClass('active');
    window['$']('#modify-TX').removeClass('active');
    window['$']('#tab2').removeClass('active');
    switch (sFundType) {
      case '':
        window['$']('#modify-ALL').addClass('active');
        window['$']('#tab1').addClass('active');
        break;
      case '1':
        window['$']('#modify-GM').addClass('active');
        window['$']('#tab1').addClass('active');
        break;
      case '2':
        window['$']('#modify-YDD').addClass('active');
        window['$']('#tab1').addClass('active');
        break;
      case '3':
        window['$']('#modify-YDY').addClass('active');
        window['$']('#tab1').addClass('active');
        break;
      case '4':
        window['$']('#modify-QYNJ').addClass('active');
        window['$']('#tab1').addClass('active');
        break;
      case '5':
        window['$']('#modify-YLJ').addClass('active');
        window['$']('#tab1').addClass('active');
        break;
      case '6':
        window['$']('#modify-SB').addClass('active');
        window['$']('#tab1').addClass('active');
        break;
      case '7':
        window['$']('#modify-YLJJ').addClass('active');
        window['$']('#tab1').addClass('active');
        break;
      case '8':
        window['$']('#modify-TX').addClass('active');
        window['$']('#tab2').addClass('active');
        break;
    }
  }
  // 批量修改判断
  selectCheck() {
    let that = this;
    let checkedItem = [];
    let checkItem = [];
    let sStepArry = [];
    let sOprArry = [];
    _.forEach(this.modifyTableComponent.instance.dataList, (item, index) => {
      if (item.isChecked) {
        checkedItem.push(_.cloneDeep(item));
      }
    });
    if (checkedItem.length == 0) {
      window['swal']("提示", "请选择一条或多条记录", "warning");
    } else {
      // 排除正常状态的指标
      checkItem = _.filter(checkedItem, function (it: any) {
        return it.sStep != '1';
      })
      if (checkItem.length == 0) {
        this.selectChange();
      } else {
        // 循环取出操作人
        _.forEach(checkItem, i => {
          sOprArry.push(_.cloneDeep(i.sOpr));
          sStepArry.push(_.cloneDeep(i.sStep));
        })
        // 去重
        let sopr = _.uniq(sOprArry);
        // 去除当前操作人,null,''
        let _sopr = _.filter(sopr, function (opr: any) {
          return opr != that.user && opr != null && opr != '';
        })
        if (_sopr.length == 0) {
          if (_.includes(sStepArry, '3') || _.includes(sStepArry, '4')) {
            window['swal']("提示", "请选择正常或变更记录修改", "warning");
          } else {
            this.selectChange();
          }
        } else {
          let soprs = _sopr.join(",")
          window['swal']("提示", "不能修改 " + soprs + " 修改过的数据", "warning");
        }
      }
    }
  }
  // 下拉框标蓝
  selectChange() {
    let that = this;
    _.forEach(this.modifyTableComponent.instance.dataList, (item, index) => {
      if (item.isChecked) {
        // 封装id
        let i = index + 1;
        // 对比原对象，标蓝
        let object = that.cloneList[index];
        if (that.f1 != '') {
          item.f1 = that.f1;
          let id = "#modify-table tbody tr:nth-child(" + i + ") td div[id='f1']";
          if (item.f1 != object.f1) {
            window['$'](id).addClass('triangle-topleft');
          } else {
            window['$'](id).removeClass('triangle-topleft');
          }
        }
        if (that.f2 != '') {
          item.f2 = that.f2;
          let id = "#modify-table tbody tr:nth-child(" + i + ") td div[id='f2']";
          if (item.f2 != object.f2) {
            window['$'](id).addClass('triangle-topleft');
          } else {
            window['$'](id).removeClass('triangle-topleft');
          }
        }
        if (that.f3 != '') {
          item.f3 = that.f3;
          let id = "#modify-table tbody tr:nth-child(" + i + ") td div[id='f3']";
          if (item.f3 != object.f3) {
            window['$'](id).addClass('triangle-topleft');
          } else {
            window['$'](id).removeClass('triangle-topleft');
          }
        }
      }
    })
  }

}
